<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span='12'>
            <a-form-item label='项目简称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-popup
                v-decorator="['projectName',validatorRules.projectShortName]"
                :trigger-change='true'
                org-fields='id,short_name'
                dest-fields='projectId,projectName'
                code='pm_project_select'
                @callback='popupCallback'
                :disabled='isAdd===2'
              />
              <input v-decorator="['projectId']" v-show='false'></input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='专题名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-popup
                v-decorator="['subjectName',validatorRules.subjectName]"
                :trigger-change='true'
                org-fields='id,subject_name'
                dest-fields='subjectId,subjectName'
                code='pm_subject_select'
                :param='{projectId: model.projectId}'
                @callback='popupCallback'
                :disabled='isAdd===2'
              />
              <input v-decorator="['subjectId']" v-show='false'></input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="目标名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['targetName',validatorRules.targetName]" :disabled='isAdd===2'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="完成标志" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['finishFlag',validatorRules.finishFlag]" :disabled='isAdd===2'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="专题开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择预计开始时间" v-decorator="['playStartTime']" disabled
                      :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="专题结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择预计结束时间" v-decorator="['playEndTime']" disabled
                      :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="预计开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-date-picker placeholder="请选择预计开始时间" v-decorator="['startTime',validatorRules.startTime]" style="width: 100%" :disabledDate='disabledPreDate' :disabled='isAdd===2'/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="预计结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-date-picker placeholder="请选择预计结束时间" v-decorator="['endTime',validatorRules.endTime]" style="width: 100%" :disabledDate='disabledPreDate' :disabled='isAdd===2'/>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="理论得分" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['weight',validatorRules.weight]" placeholder="请输入理论得分" :disabled='isAdd===2'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="目标描述" :labelCol="labelCol2" :wrapperCol="wrapperCol2">
              <a-textarea v-decorator="['targetDes',validatorRules.targetDes]" :autoSize='{minRows:4}' :disabled='isAdd===2' />
            </a-form-item>
          </a-col>
          <!--确认部分-->
          <a-col :span="12"  v-if='isAdd===2'>
            <a-form-item label="是否完成" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-decorator="['isFinish',validatorRules.isFinish]" :trigger-change="true"
                                 dictCode="yes_no"/>
            </a-form-item>
          </a-col>
          <a-col :span="12" v-if='isAdd===2'>
            <a-form-item label="实际得分" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['score']" placeholder="请输入得分" style='width: 100%'></a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span='12' v-if='isAdd===2'>
            <a-form-item label='确认人' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['confirmorName',validatorRules.confirmorName]" placeholder='请输入确认人'
                       style='width: 100%' />
            </a-form-item>
          </a-col>
          <a-col :span='12' v-if='isAdd===2'>
            <a-form-item label='确认时间' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-date placeholder='确认时间' v-decorator="['confirmorTime',validatorRules.confirmorTime]"
                      :trigger-change='true' style='width: 100%' />
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if='isAdd===2'>
            <a-form-item label="确认意见" :labelCol="labelCol2" :wrapperCol="wrapperCol2">
              <a-textarea v-decorator="['confirmorDes',validatorRules.confirmorDes]" :autoSize='{minRows:4}' />
            </a-form-item>
          </a-col>

          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
    <hf-subject-select-modal ref="hfSubjectSelectModal" :multiple="false" @hf-subject-select="hfSubjectSelect"/>
    <hf-project-select-modal ref="hfProjectSelectModal" :multiple="false" @hf-pm-project-select="hfPmProjectSelect"/>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import HfSubjectSelectModal from '@views/hifar/pm/modules/HfSubjectSelectModal'
  import HfProjectSelectModal from '@views/hifar/pm/modules/HfProjectSelectModal'
  import moment from 'moment'

  export default {
    name: 'HfPmProjectTargetsForm',
    components: {
      HfSubjectSelectModal,
      HfProjectSelectModal
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        form: this.$form.createForm(this),
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 }
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 }
        },
        confirmLoading: false,
        validatorRules: {
          confirmorDes: {
            rules: [
              { required: true, message: '请输入确认意见!' }

            ]
          },
          startTime: {
            rules: [
              { required: true, message: '请选择开始时间!'}
            ]
          },
          endTime: {
            rules: [
              { required: true, message: '请选择结束时间!'}
            ]
          },
          subjectName: {
            rules: [
              { required: true, message: '请选择专题!' }
            ]
          },
          targetName: {
            rules: [
              { required: true, message: '请输入目标名称!' }
            ]
          },
          targetDes: {
            rules: [
              { required: true, message: '请输入目标描述!' }
            ]
          },
          finishFlag: {
            rules: [
              { required: true, message: '请输入完成标志!' }
            ]
          },
          isFinish: {
            rules: [
              { required: true, message: '请选择是否完成!' }
            ]
          },
          projectShortName: {
            rules: [
              { required: true, message: '请选择项目!' }
            ]
          },
          weight: {
            rules: [
              { required: true, message: '请选择理论得分!' },
              { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!' }
            ]
          }
        },
        url: {
          add: "/pm/hfPmProjectTargets/add",
          edit: "/pm/hfPmProjectTargets/edit",
          queryById: "/pm/hfPmProjectTargets/queryById"
        },
        fields:[
          'createBy','createTime','deleteFlag','remarks','projectId','projectCode','projectName','playEndTime','playStartTime',
          'subjectId','subjectCode','subjectName','targetCode','targetName','targetDes','finishFlag','isFinish','weight','score','startTime','endTime',
          'confirmorDes','confirmorName','confirmorTime'
        ],
        defaultModel: {},
        isAdd :1
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      add() {
        let defaultObj = {}
        let {
          selectedSubName,
          selectedName,
          selectedKeys,
          selectedSubKeys,
          selectedCode,
          selectedSubCode,
          selectedTreeType,
          selectedStartTime,
          selectedEndTime
        } = this.defaultModel
        if (selectedTreeType === 'project') {
          defaultObj = {
            projectName: selectedName,
            projectId: selectedKeys,
            projectCode: selectedCode,
            weight:'100',
            isFinish:'no'
          }
        } else if (selectedTreeType === 'subject') {
          defaultObj = {
            projectName: selectedName,
            projectId: selectedKeys,
            projectCode: selectedCode,
            subjectName: selectedSubName,
            subjectCode: selectedSubCode,
            subjectId: selectedSubKeys,
            playStartTime:selectedStartTime,
            playEndTime:selectedEndTime,
            weight:'100',
            isFinish:'no'

          }
        }
        this.edit(defaultObj);
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.model.confirmorName = this.$store.getters.userInfo.username
        this.model.confirmorTime = moment().format('YYYY-MM-DD')
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,this.fields))
          this.form.setFieldsValue({ playStartTime: this.defaultModel.selectedStartTime })
          this.form.setFieldsValue({ playEndTime: this.defaultModel.selectedEndTime })
        })
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          });
        }
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            console.log("表单提交数据",formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,this.fields))
      },
      subjectNameClick() {
        this.$nextTick(() => {
          this.$refs.hfSubjectSelectModal.title = '选择主题'
          this.$refs.hfSubjectSelectModal.visible = true
        })
      },
      hfSubjectSelect(data) {
        this.form.setFieldsValue({
          subjectId: data.id,
          subjectName: data.subjectName,
          subjectCode:data.subjectCode,
          projectId:data.projectId
        })
      },
      projectShortNameClick() {
        this.$nextTick(() => {
          this.$refs.hfProjectSelectModal.title = '选择项目'
          this.$refs.hfProjectSelectModal.visible = true
        })
      },
      hfPmProjectSelect(data) {
        this.form.setFieldsValue({
          projectId: data.id,
          projectName: data.shortName,
          projectCode: data.code
        })
      },
      disabledPreDate(current){
        let currentTime = current.valueOf()
        let {playStartTime,playEndTime} = this.form.getFieldsValue(['playStartTime','playEndTime'])
        playStartTime = moment(playStartTime).valueOf()
        playEndTime = moment(playEndTime).valueOf()
        if(currentTime > playStartTime && currentTime < playEndTime)return false
        return true
      }
    }
  }
</script>